package com.dongwu.manager.web;

import java.util.ArrayList;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;

import com.dongwu.common.dto.PagingVO;
import com.dongwu.common.dto.Result;
import com.dongwu.common.utils.Exceptions;
import com.dongwu.common.web.BaseController;
import com.dongwu.common.web.Servlets;
import com.dongwu.manager.entity.Device;
import com.dongwu.manager.service.DeviceProductRecordService;
import com.dongwu.manager.service.DeviceService;
import com.dongwu.manager.service.SettingService;
import com.dongwu.security.entity.User;
import com.dongwu.security.service.IUserService;
import com.dongwu.security.utils.SecurityUtils;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/manager/device")
public class DeviceController extends BaseController<Device, String> {
	@Resource
	private DeviceProductRecordService deviceProductRecordService;

	@Resource
	private DeviceService deviceService;
	@Resource
	private SettingService settingService;
	@Resource
	private IUserService iuService;

	// @Value("${dongwu.selectcity}")
	// private String city;

	// 在所有@requestMappiing执行之前执行
	// @ModelAttribute
	// public void getEntity(@RequestParam(value = "id", defaultValue = "-1")
	// String id, Model model) {
	// if (!String.valueOf(id).equals("-1")) {
	// Device product = deviceService.get(id);
	// product.setUser(new User());
	// model.addAttribute("entity", product);
	// }
	// }
	/**
	 * 设备分布地图
	 * 
	 * @return
	 */
	@RequestMapping(value = "/remoteMonitoring")
	public String map() {
		return getPagePath("device-remoteMonitoring");
	}

	/**
	 * 保存设备并返回实体
	 * 
	 * @return
	 */
	@RequestMapping(value = "/saveReturn")
	@ResponseBody
	public Result saveReturn(Device entity) {
		try {
			if (!SecurityUtils.hasRole(this.getAddRole())) {
				return Result.denyResult();
			}
			return Result.successResult(baseService.save(entity));
		} catch (Exception e) {
			String msg = Exceptions.getMessage(e);
			logger.error(msg, e);
			return Result.errorResult(msg);
		}
	}

	/**
	 * 修改
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/update")
	@ResponseBody
	public Result update(/* @RequestBody */@ModelAttribute("entity") Device entity) {
		try {
			if (!SecurityUtils.hasRole(this.getEditRole())) {
				return Result.denyResult();
			}
			if(entity.getAppTemplate() != null){
				if(entity.getAppTemplate().getTemplateType() != null){
					if("005".equals(entity.getAppTemplate().getTemplateType().getTemplateTypeSn())){
						entity.setTemplateTypeSn("002");
					}else if("006".equals(entity.getAppTemplate().getTemplateType().getTemplateTypeSn()) || "007".equals(entity.getAppTemplate().getTemplateType().getTemplateTypeSn())
                            || "008".equals(entity.getAppTemplate().getTemplateType().getTemplateTypeSn())|| "009".equals(entity.getAppTemplate().getTemplateType().getTemplateTypeSn())){
						entity.setTemplateTypeSn("003");
					}else{
						entity.setTemplateTypeSn("001");
					}
				}
			}
			baseService.update(entity);
			return Result.successResult();
		} catch (Exception e) {
			String msg = Exceptions.getMessage(e);
			logger.error(msg, e);
			return Result.errorResult(msg);
		}
	}

	/**
	 * 设备分布地图
	 * 
	 * @return
	 */
	@RequestMapping(value = "/gotolist")
	public String gotolist(String name, HttpServletResponse response) {
		String cookieName = "city";
		Cookie cookie = new Cookie(cookieName, name);
		cookie.setMaxAge(20); // 存活期为10秒
		response.addCookie(cookie);
		return getPagePath("device-list");
	}

//	/**
//	 * 
//	 * @param remark
//	 * @return
//	 * @throws ParseException
//	 */
//	@RequestMapping(value = "/addRecord")
//	@ResponseBody
//	public Result addRecord(String remark, String startTime, String endTime,
//			@RequestParam(value = "ids[]") String[] ids, @RequestParam(value = "pids[]") String[] pids)
//			throws ParseException {
//		List<DeviceProductRecord> insdpr = new ArrayList<DeviceProductRecord>();
//		List<DeviceProductRecord> upddpr = new ArrayList<DeviceProductRecord>();
//		for (int i = 0; i < ids.length; i++) {
//			User user = deviceService.get(ids[i]).getUser();
//			for (int j = 0; j < pids.length; j++) {
//				DeviceProductRecord r = new DeviceProductRecord();
//				r.setUser(user);
//				r.setDeviceid(ids[i]);
//				if (startTime != "") {
//					r.setStartTime(DateUtils.parseDate(startTime, DateUtils.PATTERN_DATE_TIME));
//				}
//				if (endTime != "") {
//					r.setEndTime(DateUtils.parseDate(endTime, DateUtils.PATTERN_DATE_TIME));
//				}
//				r.setProductid(pids[j]);
//				r.setRemark(remark);
//				// 获取当前设备的所有投放记录
//				List<DeviceProductRecord> dprList = deviceProductRecordService.findByDeviceid(ids[i]);
//				if (dprList.size() != 0) {
//					boolean isexist = true;
//					// 如果记录存在则遍历记录
//					for (DeviceProductRecord dpr : dprList) {
//						// 如果已投放当前商品则更新
//						if (dpr.getProductid().equals(pids[j])) {
//							r.setId(dpr.getId());
//							upddpr.add(r);
//							isexist = false;
//						}
//					}
//					// 如果当前设备的当前商品不存在则添加
//					if (isexist) {
//						insdpr.add(r);
//					}
//				} else {
//					// 设备无投放记录时添加
//					insdpr.add(r);
//				}
//
//			}
//		}
//		deviceProductRecordService.batchInsert(insdpr);
//		deviceProductRecordService.batchUpdate(upddpr);
//		return Result.successResult();
//
//	}
	//
	// /**
	// *
	// * @return
	// */
	// @RequestMapping(value = "/selectcity")
	// @ResponseBody
	// public Result selectcity() {
	// try {
	// List<String> citys =
	// Splitter.on(",").trimResults().omitEmptyStrings().splitToList(city);
	//
	// return Result.successResult(citys);
	//
	// } catch (Exception e) {
	// String msg = Exceptions.getMessage(e);
	// logger.error(msg, e);
	// return Result.errorResult(msg);
	// }
	//
	// }

	/**
	 *
	 * @return
	 */
	@RequestMapping(value = "/getCityCount")
	@ResponseBody
	public Result getCityCount(HttpServletRequest request) {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, SEARCH_PARAM_PREFIX);
		super.filterDataPermission(searchParams);
		return Result.successResult(deviceService.findCityCount(searchParams));

	}

	@Override
	@RequestMapping(value = "/findAll")
	@ResponseBody
	public Result findAll(HttpServletRequest request) {
		try {

			Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, SEARCH_PARAM_PREFIX);
			// 统一过滤数据权限
			filterDataPermission(searchParams);

			Iterable<Device> list = baseService.findList(searchParams);
			return Result.successResult(list);
		} catch (Exception e) {
			String msg = Exceptions.getMessage(e);
			logger.error(msg, e);
			return Result.errorResult(msg);
		}
	}

	/**
	 * 审核通过
	 * 
	 * @return
	 */
	// @RequestMapping(value = "/approval/{id}")
	// @ResponseBody
	// public Result approval(@RequestParam("id") String id,@RequestParam("id")
	// String remark,@RequestParam("id") String type) {
	// try {
	// deviceService.approval(id);
	// return Result.successResult();
	// } catch (Exception e) {
	// String msg = Exceptions.getMessage(e);
	// logger.error(msg, e);
	// return Result.errorResult(msg);
	// }
	// }

	/**
	 * 商品状态审核
	 * 
	 * @param id
	 * @param remark
	 * @param type
	 * @return
	 */
	@RequestMapping(value = "/check")
	@ResponseBody
	public Result check(@RequestParam(value = "id", required = true) String id,
			@RequestParam(value = "remark", required = true) String remark,
			@RequestParam(value = "type", required = true) String type) {
		try {
			deviceService.check(id, type, remark);
			return Result.successResult();
		} catch (Exception e) {
			String msg = Exceptions.getMessage(e);
			logger.error(msg, e);
			return Result.errorResult(msg);
		}
	}

	/**
	 * 获取当前用户的商品总数
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getcount")
	@ResponseBody
	public Result getcount(HttpServletRequest request) {
		Long dprcount = null;
		// 获取当前登录的用户
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		userDetails.getUsername();
		if (userDetails.getUsername().equals("admin")) {
			Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, SEARCH_PARAM_PREFIX);
			super.filterDataPermission(searchParams);
			dprcount = deviceService.getCount(searchParams, null);
		} else {
			// 获取当前登录的用户详情
			User a = iuService.findByLoginName(userDetails.getUsername());
			dprcount = deviceService.getCount(null, a.getId());
		}
		PagingVO paging = new PagingVO(new ArrayList<Device>(), Integer.parseInt(String.valueOf(dprcount)), 0, 10);
		return Result.successResult(paging);
	}
}
